package com.iplant.mes.controller.sfc;

import com.iplant.base.po.Pagination;
import com.iplant.base.po.ServiceResult;
import com.iplant.base.utils.RetCode;
import com.iplant.base.utils.serializer.CloneTool;
import com.iplant.base.utils.general.StringUtils;
import com.iplant.basic.controller.BasicController;
import com.iplant.basic.service.po.bms.BMSEmployee;
import com.iplant.mes.service.SFCFrockBindService;
import com.iplant.mes.service.SFCService;
import com.iplant.mes.service.po.sfc.SFCFrockBindRecord;
import com.iplant.mes.service.po.sfc.SFCTaskSelf;
import com.iplant.mes.service.po.sfc.frockBind.SFCBindComponent;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 工装绑定工件记录
 *
 * @author YouWang·Peng
 * 2023-12-8 09:59:42
 */
@RestController
@RequestMapping("/api/SFCFrockBindRecord")
@Api(tags = "工装绑定接口")
public class SFCFrockBindRecordController extends BasicController<SFCFrockBindRecord> {
    private static final Logger logger = LoggerFactory.getLogger(SFCFrockBindRecordController.class);

    public SFCFrockBindRecordController() {
        super(SFCFrockBindRecord.class);
    }

    @Autowired
    SFCService mSFCService;

    @Autowired
    SFCFrockBindService mSFCFrockBindService;

    /**
     * 绑定
     */
    @PostMapping("/Binding")
    public Object Binding(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            // 获取参数
            List<SFCFrockBindRecord> wSFCFrockBindRecordList = CloneTool.CloneArray(wParam.get("data"),
                    SFCFrockBindRecord.class);
            if (wSFCFrockBindRecordList == null || wSFCFrockBindRecordList.size() == 0
                    || wSFCFrockBindRecordList.stream().anyMatch(p -> p.FrockLedgerID <= 0 || StringUtils.isEmpty(p.ComponentCode))) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<Integer> wServiceResult = mSFCService.SFC_BindingFrockBindRecord(wLoginUser,
                    wSFCFrockBindRecordList);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    /**
     * 解绑
     */
    @PostMapping("/UnBinding")
    public Object UnBinding(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            // 获取参数
            List<SFCFrockBindRecord> wSFCFrockBindRecordList = CloneTool.CloneArray(wParam.get("data"),
                    SFCFrockBindRecord.class);
            if (wSFCFrockBindRecordList == null || wSFCFrockBindRecordList.size() == 0
                    || wSFCFrockBindRecordList.stream().anyMatch(p -> p.FrockLedgerID <= 0 || StringUtils.isEmpty(p.ComponentCode))) {
                return wResult;
            }

            ServiceResult<Integer> wServiceResult = mSFCService.SFC_UnBindingFrockBindRecord(wLoginUser,
                    wSFCFrockBindRecordList);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    /**
     * 托盘绑定工件
     */
    @PostMapping("/TrayBindingComponents")
    public Object TrayBindingComponents(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {
            BMSEmployee wLoginUser = GetSession(request);
            //托盘码
            String wTrayCode = StringUtils.parseString(wParam.get("TrayCode"));
            //元件码（多个以逗号分隔）
            String wComponentCodes = StringUtils.parseString(wParam.get("ComponentCodes"));
            //模具码（只支持一个）
            String wMoldCode = StringUtils.parseString(wParam.get("MoldCode"));
            //当前工位已开工的任务列表
            List<SFCTaskSelf> wSFCTaskSelfList = CloneTool.CloneArray(wParam.get("data"), SFCTaskSelf.class);
            //数据校验
            if (StringUtils.isEmpty(wTrayCode) || StringUtils.isEmpty(wComponentCodes) || wSFCTaskSelfList.size() == 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<Integer> wServiceResult = mSFCService.SFC_TrayBindingComponents(wLoginUser, wTrayCode,
                    wComponentCodes, wSFCTaskSelfList, wMoldCode);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    /**
     * 托盘解绑工件
     */
    @PostMapping("/TrayUnBindComponents")
    public Object TrayUnBindComponents(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {
            BMSEmployee wLoginUser = GetSession(request);
            //托盘码
            String wTrayCode = StringUtils.parseString(wParam.get("TrayCode"));
            //数据校验
            if (StringUtils.isEmpty(wTrayCode)) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<Integer> wServiceResult = mSFCService.SFC_TrayUnBindComponents(wLoginUser, wTrayCode);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    /**
     * 保存托盘绑定
     */
    @PostMapping("/SaveTrayBindingComponents")
    public Object SaveTrayBindingComponents(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {
            BMSEmployee wLoginUser = GetSession(request);
            //托盘码
            String wTrayCode = StringUtils.parseString(wParam.get("TrayCode"));
            //元件码（多个以逗号分隔）
            String wComponentCodes = StringUtils.parseString(wParam.get("ComponentCodes"));
            //当前工位已开工的任务列表
            List<SFCTaskSelf> wSFCTaskSelfList = CloneTool.CloneArray(wParam.get("data"), SFCTaskSelf.class);
            //数据校验
            if (StringUtils.isEmpty(wTrayCode) || StringUtils.isEmpty(wComponentCodes) || wSFCTaskSelfList.size() <= 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<Integer> wServiceResult = mSFCService.SFC_SaveTrayBindingComponents(wLoginUser, wTrayCode,
                    wComponentCodes, wSFCTaskSelfList);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    /**
     * 获取元件对应工单（判断元件是否可以绑定托盘）
     */
    @PostMapping("/GetWorkOrder")
    public Object GetWorkOrder(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            //元件号
            String wComponentCode = StringUtils.parseString(wParam.get("ComponentCode"));
            //当前工位已开工的任务列表
            List<SFCTaskSelf> wSFCTaskSelfList = CloneTool.CloneArray(wParam.get("data"), SFCTaskSelf.class);

            ServiceResult<SFCTaskSelf> wServiceResult = mSFCFrockBindService.SFC_GetWorkOrderByComponentCode(wLoginUser,
                    wComponentCode,
                    wSFCTaskSelfList);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 托盘绑定工单
     */
    @PostMapping("/TrayBindingWorkOrder")
    public Object TrayBindingWorkOrder(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            //托盘码
            String wTrayCode = StringUtils.parseString(wParam.get("TrayCode"));
            //绑定状态
            int wStatus = StringUtils.parseInt(wParam.get("Status"));
            //工单信息
            List<SFCBindComponent> wSFCBindComponentList = CloneTool.CloneArray(wParam.get("data"),
                    SFCBindComponent.class);
            if (StringUtils.isEmpty(wTrayCode) || wSFCBindComponentList == null || wSFCBindComponentList.size() == 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<Integer> wServiceResult = mSFCFrockBindService.SFC_TrayBindingWorkOrder(wLoginUser, wTrayCode,
                    wSFCBindComponentList, wStatus);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 条件查询所有记录
     */
    @Override
    @GetMapping("/All")
    public Object All(HttpServletRequest request) {
        Object wResult = new Object();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            Map<String, Object> wParams = GetParamsMap(request);
            Pagination wPagination = GetPagination(request, mClazz);

            ServiceResult<List<SFCFrockBindRecord>> wServiceResult =
                    mSFCFrockBindService.SFC_QueryFrockBindRecordAll(wLoginUser, wParams, wPagination);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServiceResult.Result, wPagination.getTotalPage());
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 根据条码获取条码类型
     */
    @GetMapping("/GetComponentTypeByBarCode")
    public Object GetComponentTypeByBarCode(HttpServletRequest request) {
        Object wResult = new Object();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            String wBarCode = StringUtils.parseString(request.getParameter("BarCode"));
            if (StringUtils.isEmpty(wBarCode)) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<String> wServiceResult = mSFCFrockBindService.SFC_GetComponentTypeByBarCode(wLoginUser,
                    wBarCode);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wBarCode, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }
}
